package com.hzw.code.config;

import com.hzw.code.config.property.SwaggerProperty;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

/**
 * swagger配置类
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

	@Autowired
	SwaggerProperty swaggerProperty;

	@Bean
	public Docket api() throws Exception{
		//添加head参数start
		ParameterBuilder tokenPar = new ParameterBuilder();
		List<Parameter> pars = new ArrayList<Parameter>();
		String tokenKey = swaggerProperty.getTokenKey();

		if(StringUtils.isNotBlank(tokenKey)){
			tokenPar.name(tokenKey).description("令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
		}

		pars.add(tokenPar.build());
		//添加head参数end
		return new Docket(DocumentationType.SWAGGER_2)
				.select()
				.apis(RequestHandlerSelectors.basePackage(swaggerProperty.getBasePackage()))
				.paths(PathSelectors.any())
				.build()
				.globalOperationParameters(pars)
				.enable(swaggerProperty.getEnabled())
				 // .host("")
				.apiInfo(apiInfo());
	}

	public ApiInfo apiInfo() throws Exception {
		return new ApiInfoBuilder().title(swaggerProperty.getTitle()).description(swaggerProperty.getDescription())
				.termsOfServiceUrl(swaggerProperty.getTermsOfServiceUrl())
				.contact(new Contact(swaggerProperty.getAuthorName(), swaggerProperty.getAuthorUrl(), swaggerProperty.getAuthorEmail())).version(swaggerProperty.getVersion())
				.build();
	}
}
